/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.freedoit;

import java.awt.AWTException;
import java.awt.Font;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Enumeration;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.freedoit.gui.AboutDialog;
import org.freedoit.gui.DoitFrame;
import org.freedoit.gui.LoginDialog;
import org.freedoit.gui.SettingDialog;
import org.freedoit.util.LogUtils;
import org.freedoit.util.Utils;

/**
 *
 * @author wanglei
 */
public class FreeDoit {
    private static final Logger logger = LogUtils.getLogger(FreeDoit.class);;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        //</editor-fold>
        /* Create and display the form */

        JFrame.setDefaultLookAndFeelDecorated(true);  
        JDialog.setDefaultLookAndFeelDecorated(true);
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                // Set Skin;
                try {
                    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                    logger.error(ex);
                } catch (ClassNotFoundException ex) {
                    logger.error(ex);
                } catch (InstantiationException ex) {
                    logger.error(ex);
                } catch (IllegalAccessException ex) {
                    logger.error(ex);
                }
                
                // set default font here
                initGlobalFontSetting(FreeDoitConfig.getDefaultFont());
                
                //
                String userName = FreeDoitConfig.getLatestUser();
                if (userName == null || "".endsWith(userName)) {
                    popupLogin(true);
                } else {
                    String password = FreeDoitConfig.getUserPassword(userName);
                    if (password == null || "".equals(password)) {
                        popupLogin(true);
                    } else {
                        if (!LoginDialog.doLogin(userName, password, new StringBuffer())) {
                            popupLogin(true);
                        }
                    }
                }
                
                final DoitFrame frame = new DoitFrame();
                buildSysTray(frame);
                
                frame.setVisible(true);
            }
        });
    }
    
    private static void buildSysTray(final DoitFrame window) {
        if (SystemTray.isSupported()) {
            final SystemTray st = SystemTray.getSystemTray();

            final TrayIcon trayIcon = new TrayIcon(
                    new javax.swing.ImageIcon(FreeDoit.class.getResource("/icon/freedoit_16.png")).getImage(),
                    FreeDoitConfig.getText("tray.tooltip"));
            trayIcon.addMouseListener(new MouseAdapter() {
                 public   void  mouseClicked(MouseEvent e) {  
                    // TODO Auto-generated method stub 
                    if (!window.isVisible()) {
                        window.setVisible(true);
                    }  
                }   
            });
            
            // Popup Menu
            PopupMenu pop = new PopupMenu();
            Font menuFont = FreeDoitConfig.getFont(0, 12);
            pop.setFont(menuFont);
            int iFillCount = 2; // Fill some space in the menu name so that the size of menu can be larger
            MenuItem menuItem = new MenuItem(Utils.fillSpace(
                    FreeDoitConfig.getText("tray.menu.open"), iFillCount));
            menuItem.setFont(menuFont);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (!window.isVisible()) {
                        window.setVisible(true);
                    }
                }
                
            });
            pop.add(menuItem);

            menuItem = new MenuItem(Utils.fillSpace(
                    FreeDoitConfig.getText("tray.menu.sync"), iFillCount));
            menuItem.setFont(menuFont);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //
                    window.performSync();
                }
                
            });
            pop.add(menuItem);

            menuItem = new MenuItem(Utils.fillSpace(
                    FreeDoitConfig.getText("tray.menu.setting"), iFillCount));
            menuItem.setFont(menuFont);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //
                    SettingDialog dialog = new SettingDialog(window, true);
                    Utils.displayAtCentralScreen(dialog);
                    dialog.setVisible(true);
                }
                
            });
            pop.add(menuItem);

            menuItem = new MenuItem(Utils.fillSpace(
                    FreeDoitConfig.getText("tray.menu.about"), iFillCount));
            menuItem.setFont(menuFont);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //
                    AboutDialog dialog = new AboutDialog(window, true);
                    Utils.displayAtCentralScreen(dialog);
                    dialog.setVisible(true);
                }
                
            });
            pop.add(menuItem);

            menuItem = new MenuItem(Utils.fillSpace(
                    FreeDoitConfig.getText("tray.menu.logout"), iFillCount));
            menuItem.setFont(menuFont);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    window.setVisible(false);
                    popupLogin(true);
                }
                
            });
            pop.add(menuItem);

            menuItem = new MenuItem(Utils.fillSpace(
                    FreeDoitConfig.getText("tray.menu.exit"), iFillCount));
            menuItem.setFont(menuFont);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    st.remove(trayIcon);
                    clearBeforeExit();
                    System.exit(0);
                }
            });
            pop.add(menuItem);
            
            trayIcon.setPopupMenu(pop);
            try {
                st.add(trayIcon);
            } catch (AWTException ex) {
                logger.error(ex);
            }
        }
    }
    
    public static void initGlobalFontSetting(Font fnt){
        FontUIResource fontRes = new FontUIResource(fnt);
        for(Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();){
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if(value instanceof FontUIResource) {
                UIManager.put(key, fontRes);
            }
        }
    }
    
    private static void clearBeforeExit() {
        httpclient.getConnectionManager().shutdown();
        FreeDoitConfig.saveConfig();
    }
    
    private static DefaultHttpClient httpclient = new DefaultHttpClient();
    
    public synchronized static DefaultHttpClient getHttpClient() {
        return httpclient;
    }
    
    private synchronized static boolean popupLogin(final boolean exitOnClosing) {
        
        LoginDialog dialog = new LoginDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                if (exitOnClosing) {
                    clearBeforeExit();
                    System.exit(1);
                }
            }
        });
        dialog.setVisible(true);
        
        // save user name
        String userName = dialog.getUserName();
        //FreeDoitConfig.setProperty(FreeDoitConfig.KEY_LAST_USER_NAME, userName);
        
        // save password if remember me is set
        if (dialog.isLogin()) {
            if (dialog.isRememberMe()) {
                FreeDoitConfig.updateLatestUserInfo(userName, dialog.getPassword());
            } else {
                FreeDoitConfig.updateLatestUserInfo(userName, null);
            }
        } 
        
        return dialog.isLogin();
    }
    
    public synchronized static boolean popupLogin() {
        return popupLogin(false);
    }
}
